<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { dsConst } from './ds_const'
import { getWorkPlan, getDoctorInfo } from '@/services/doctor'
import { registerMedicalAppointment, mockPay } from '@/services/payment'
import type { BaseDoctorInfo, WorkPlanItem, WorkPlanResult } from '@/types/doctor'
import { ref } from 'vue'
import dayjs from 'dayjs'
import type { PaymentReqParams } from '@/types/payment'
import { generateRandomDigitString } from '@/utils/randomString'

const query = defineProps<{
  deptSubId: number
  doctorId: number
  date: string
}>()
const { json, notice } = dsConst()
const date = ref(query.date)
const doctorId = ref(query.doctorId)
const deptSubId = ref(query.deptSubId)
const doctor = ref<BaseDoctorInfo>()
const schedule = ref<WorkPlanItem>()
const workPlanId = ref<number>()
const scheduleId = ref<number>()
const selectedSlot = ref<number | null>(null)

//处理选择挂号时间事件
const clickScheduleHandler = (cWorkPlanId: number, cScheduleId: number, cSlot: number) => {
  workPlanId.value = cWorkPlanId
  scheduleId.value = cScheduleId
  for (let one of schedule.value) {
    if (one.style === 'item disable') {
      selectedSlot.value = null
      continue
    }
    one.style = 'item'
    if (one.slot === cSlot) {
      console.log(one)
      one.style = 'item active'
      selectedSlot.value = one.slot
    }
  }
  console.log(selectedSlot.value)
}

//处理点击去支付事件
const submitHandler = () => {
  if (selectedSlot.value === null) {
    uni.showToast({
      icon: 'error',
      title: '选择预约时间',
    })
    return
  }
  uni.showModal({
    title: '提示信息',
    content: '确定付款挂号？',
    success: async (res) => {
      if (res.confirm) {
        let data: PaymentReqParams = {
          workPlanId: workPlanId.value!,
          scheduleId: scheduleId.value!,
          date: date.value,
          doctorId: doctorId.value,
          deptSubId: deptSubId.value,
          amount: doctor!.value!.price,
          slot: selectedSlot.value!,
        }
        await registerMedicalAppointment(data).then((res) => {
          let payrReqResult = res.result
          if (!payrReqResult.outTradeNo) {
            uni.showToast({
              icon: 'none',
              title: '该时段挂号失败',
            })
          } else {
            uni.showModal({
              title: '提示信息',
              content: '确认挂号并支付？',
              confirmText: '模拟支付',
              cancelText: '取消',
              success: async (res) => {
                if (res.confirm) {
                  let data = {
                    outTradeNo: payrReqResult.outTradeNo,
                    transactionId: generateRandomDigitString(dayjs().format('YYYYMMDD'), 12),
                  }
                  await mockPay(data).then((res) => {
                    if (res.result) {
                      uni.showToast({
                        icon: 'success',
                        title: '付款成功',
                      })
                    } else {
                      uni.showToast({
                        icon: 'none',
                        title: '付款异常，请联系客服',
                      })
                    }
                    setTimeout(function () {
                      uni.switchTab({
                        url: '/pages/registration_list/registration_list',
                      })
                    }, 1500)
                  })
                } else if (res.cancel) {
                  uni.showToast({
                    icon: 'none',
                    title: '取消支付',
                  })
                  setTimeout(function () {
                    uni.switchTab({
                      url: '/pages/registration_list/registration_list',
                    })
                  }, 1500)
                }
              },
            })
          }
        })
      }
    },
  })
}

onLoad(async () => {
  await Promise.all([searchDoctorInfoById(), searchDoctorWorkPlanSchedule()])
})

//获取医生信息
const searchDoctorInfoById = () => {
  getDoctorInfo({ id: doctorId.value }).then((res) => {
    doctor.value = res.result
    doctor.value.photo = 'http://114.132.57.246:9000/hospital' + doctor.value.photo
  })
}

//获取挂号时间
const searchDoctorWorkPlanSchedule = () => {
  getWorkPlan({
    date: date.value,
    doctorId: doctorId.value,
  }).then((res) => {
    let result = res.result
    let scheduleArr = []
    let now = dayjs('2024-1-19')
    for (let one in json) {
      let rangeStart = dayjs(`${date.value} ${json[one]}`)

      let item = result.find((element: WorkPlanResult) => {
        return element.slot + '' == one
      })

      let style = null
      //如果挂今天的时段，如果该出诊时段已经过期了，就使用禁用效果的CSS样式
      if (date.value == date.value && now.isAfter(rangeStart)) {
        style = 'item disable'
      }
      //如果该时段医生不出诊，使用禁用效果的CSS样式
      else if (item == undefined) {
        style = 'item disable'
      }
      //如果该时段挂号人数已达最大值，使用禁用效果的CSS样式
      else if (item.num == item.maximum) {
        style = 'item disable'
      }
      //如果可以挂号，该时段使用正常CSS样式
      else {
        style = 'item'
      }

      scheduleArr.push({
        workPlanId: item != undefined ? item.workPlanId : null,
        scheduleId: item != undefined ? item.scheduleId : null,
        slot: one,
        range: json[one],
        style: style,
      })
    }
    schedule.value = scheduleArr
  })
}
</script>

<template>
  <view>
    <view>
      <view class="doctor" v-if="doctor">
        <u-avatar :src="doctor.photo" size="45"></u-avatar>
        <view class="info">
          <view class="row">
            <text class="name">{{ doctor.name }}</text>
            <text class="job">（{{ doctor.job }}）</text>
          </view>
          <view class="row">
            <text class="remark">{{ doctor.remark }}</text>
          </view>
          <view class="row">
            <rich-text class="desc">{{ doctor.description }}</rich-text>
          </view>
        </view>
      </view>
      <view class="schedule-container">
        <view>
          <text class="title">选择挂号时间</text>
          <u-grid :border="false" col="4">
            <u-grid-item v-for="one in schedule" :key="one.slot">
              <text
                :class="one.style"
                @click="clickScheduleHandler(one.workPlanId, one.scheduleId, one.slot)"
              >
                {{ one.range }}
              </text>
            </u-grid-item>
          </u-grid>
        </view>
        <u-parse :content="notice"></u-parse>
        <u-button type="primary" size="large" @click="submitHandler"
          >挂号费{{ doctor?.price ? doctor.price : '' }}元，去支付</u-button
        >
      </view>
    </view>
  </view>
</template>

<style lang="less">
@import url(doctor_schedule.less);
</style>
